package com.mini.common.config;

import com.google.common.cache.CacheBuilder;
import org.springframework.cache.CacheManager;
import org.springframework.cache.guava.GuavaCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author: anjl
 * @description:
 * @data: 2021/3/3
 **/


@Configuration
public class SpringCacheConfig {
    /**
     * spring缓存配置，使用guava
     *
     * @return
     */

    public static final String GROUP_LIST = "GROUP_LIST";
    public static final String TEACHER = "TEACHER";
    public static final String DEPT = "DEPT";

    public enum CacheEnum {

        /**
         *
         */
        GROUP_LIST(60 * 60),
        TEACHER(60 * 60),
        DEPT(60 * 60),
        ;
        public final int expireInSeconds;

        CacheEnum(int expireInSeconds) {
            this.expireInSeconds = expireInSeconds;
        }
    }

    @Bean
    public CacheManager cacheManager() {
        SimpleCacheManager cacheManager = new SimpleCacheManager();

        List<GuavaCache> collect = Arrays.stream(CacheEnum.values()).map(cacheEnum ->
                new GuavaCache(cacheEnum.name(),
                        CacheBuilder.newBuilder()
                                .recordStats()
                                .maximumSize(10000)
                                .expireAfterWrite(cacheEnum.expireInSeconds, TimeUnit.SECONDS)
                                .build())).collect(Collectors.toList());
        cacheManager.setCaches(collect);
        return cacheManager;
    }
}
